<script setup>
  import { loginApi } from '@/apis/user.js'
  import { ref } from 'vue'
  import { useUserStore } from '@/stores/user'
  import { onLoad } from '@dcloudio/uni-app'
  const userStore = useUserStore()
  // 定义表单数据
  const formData = ref({
    account: 'itheima3',
    password: '123456',
  })
  // 定义验证规则
  const accountRules = {
    account: {
      rules: [
        { required: true, errorMessage: '必填项' },
        { pattern: '^[a-zA-Z0-9]{6,8}$', errorMessage: '登录账号格式不正确' },
      ],
    },
    password: {
      rules: [
        { required: true, errorMessage: '请输入登录密码' },
        { pattern: '^\\d{6}$', errorMessage: '登录密码格式不正确' },
      ],
    },
  }
  // 表单实例
  const form = ref()

/*  // 得到页面栈
  const currentPages = getCurrentPages()
  const targetUrl = currentPages[currentPages.length - 1].options.redirect */

  // 路径上的url
  const redirectUrl = ref('')

  // 路径上的redirectType
  const redirectType = ref('')

  onLoad((query) => {
    redirectUrl.value = query.redirectUrl
    redirectType.value = query.redirectType
  })

  // 点击登录的方法
  const submitForm = async() => {
    try {
      const res = await form.value.validate()
      const { data } = await loginApi(res)
      userStore.token = data

      // 如果路径上有跳转的链接
      if (redirectUrl.value) {
        // 决定跳转的方法类型
        uni[redirectType.value]({
          url: redirectUrl.value,
        })
      } else {
        uni.reLaunch({
          url: '/',
        })
      }

      console.log(data)
    } catch (e) {
      console.log(e)
    }
  }
</script>
<template>
  <uni-forms
    class="login-form"
    :rules="accountRules"
    ref="form"
    :model="formData"
    validate-trigger="bind"
  >
    <uni-forms-item name="account">
      <input
        type="text"
        placeholder="请输入账号"
        v-model="formData.account"
        class="uni-input-input"
        placeholder-style="color: #818181"
      />
    </uni-forms-item>
    <uni-forms-item name="password">
      <input
        type="text"
        placeholder="请输入密码"
        v-model="formData.password"
        class="uni-input-input"
        placeholder-style="color: #818181"
      />
    </uni-forms-item>
    <button class="submit-button" @click="submitForm">登录</button>
  </uni-forms>
</template>

<style lang="scss" scoped>
  @import './styles.scss';
</style>
